package com.bhh.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * @author bhh
 * @description 关于BIO模型的服务器Handler线程
 * Handler线程去处理客户端请求
 * 和 ChatServer类
 * 和 ChatClient类 + UserInputHandler类配合使用
 *
 * @date Created in 2021-04-07 15:51
 * @modified By
 */
@Slf4j
public class ChatHandler implements Runnable {

    private ChatServer server;
    private Socket socket;

    public ChatHandler(ChatServer server, Socket socket) {
        this.server = server;
        this.socket = socket;
    }

    @Override
    public void run() {
        // 持续接受信息, 持续转发信息
        try {
            //添加新的socket到map
            server.addClient(socket);

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream())
            );
            String str = null;
            //获取客户端信息, readLine() 方法也是会让线程阻塞
            while ((str = reader.readLine()) != null){

                //判断客户端是否退出
                if (server.quit(str)) {
                    log.info("客户端[" + socket.getPort() + "] 断开连接");
                    break;
                } else {
                    String fwdMsg = "客户端[" + socket.getPort() + "] : " + str + "\n";
                    log.info(fwdMsg);

                    //转发给其他用户
                    server.forwardMessage(socket, fwdMsg);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                server.removeClient(socket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
